package com.leyou.qurtz.tasks;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.leyou.common.constants.RedisConstants;
import com.leyou.qurtz.config.AliOssProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <h3>leyou-project</h3>
 * <p></p>
 *
 * @author : hhw
 * @date : 2020-05-25 13:21
 **/
@Component("delPicQurtz")
@Slf4j
public class DeletePicTiming {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private AliOssProperties prop;

    @Autowired
    private OSS ossClient;
    /**
     *@描述  定时删除图片任务
     *@参数  []
     *@返回值  void
     *@创建人  hhw
     *@创建时间  2020/5/25
     *@修改人和其它信息
     */
    public void deletePicTiming(){
        Set<String> diffImg = stringRedisTemplate.opsForSet().difference(RedisConstants.BRAND_PIC_RESOURCE, RedisConstants.BRAND_PIC_DB_RESOURCE);
         List<String> keys = new ArrayList<String>(diffImg);
        List<String> list = keys.stream().map(s -> s.split(".com/")[1]).collect(Collectors.toList());

        if (list.size() != 0) {
            ossClient.deleteObjects(new DeleteObjectsRequest(prop.getBucketName()).withKeys(list));

            for (String key : keys) {
                stringRedisTemplate.opsForSet().remove(RedisConstants.BRAND_PIC_RESOURCE, key);
            }

            log.info("清理图片成功,时间:{}", new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
        } else log.info("无需清理图片,时间:{}", new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));

    }


}
